﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ParkingLot.Utility
{
    /// <summary>
    /// 缓冲对象(缓冲一些对象,避免反复加载引起的资源浪费)
    /// </summary>
    public class BufferObjectHelp
    {

        /// <summary>
        /// 缓存对象数量
        /// </summary>
        private static int m_SaveCount = 30;

        /// <summary>
        /// 存储所有的Collection集合
        /// </summary>
        private static Dictionary<Guid, object> m_DictBufferObject = new Dictionary<Guid, object>();

        /// <summary>
        /// 加入缓冲池
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="strGuid"></param>
        /// <param name="createFunc"></param>
        /// <returns></returns>
        public static T CreateOrGetT<T>(string strGuid, Func<T> createFunc)
        {
            Guid guid = Guid.Parse(strGuid);
            return CreateOrGetT<T>(guid, createFunc);
        }

        public static T CreateOrGetT<T>(Func<T> createFunc)
        {
            Guid guid = typeof (T).GUID;
            return CreateOrGetT<T>(guid, createFunc);
        }

        /// <summary>
        /// 加入缓冲池
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="strGuid"></param>
        /// <param name="createFunc"></param>
        /// <returns></returns>
        public static T CreateOrGetT<T>(Guid guid, Func<T> createFunc)
        {
            if (m_DictBufferObject.ContainsKey(guid))
            {
                return (T)m_DictBufferObject[guid];
            }
            else
            {
                T t = createFunc();
                if (m_DictBufferObject.Count >= m_SaveCount)
                {
                    KeyValuePair<Guid, object> keyValuePair = m_DictBufferObject.ElementAt(0);
                    m_DictBufferObject.Remove(keyValuePair.Key);
                }
                m_DictBufferObject.Add(guid, t);
                return t;
            }
        }
    }
}
